import datetime,cgi
import sys
import os
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.dist import use_library
from os import environ
from models import *

class EditProject(webapp.RequestHandler):
	global projectid

	def post(self):
		global projectid
		is_confirm = self.request.get('confirm', None)
		is_delete = self.request.get('delete', None)
		is_cancel = self.request.get('cancel', None)
		if is_confirm:
			pname=self.request.get("projname")
			pabstract=self.request.get("projabstract")
			pteamid=self.request.get("projteamids")
			pcategory=self.request.get("catsel")
			planguages=''
			languages=db.GqlQuery("SELECT * FROM languages")
			for i in languages:
				if self.request.get("l"+i.languageid) == "l"+i.languageid:
					if not planguages:
						planguages=i.languageid
					else:
						planguages=planguages+","+i.languageid
			pfields=''
			fields=db.GqlQuery("SELECT * FROM projectFields")
			for i in fields:
				if self.request.get("f"+i.fieldid) == "f"+i.fieldid:
					if not pfields:
						pfields=i.fieldid
					else:
						pfields=pfields+","+i.fieldid
			previewdate=self.request.get("projreviewdate")
			previewdate=self.request.get("projmaxmem")
			project=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid))
			for projdetails in project:
				projdetails.projectname=pname
				projdetails.category=pcategory
				projdetails.languages=planguages
				projdetails.abstract=pabstract
				projdetails.teamid=pteamid
				projdetails.reviewdate=previewdate
				projdetails.fieldnames=pfields
				projdetails.put()
			teammembers=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %pteamid)
			for mem in teammembers:
				notifymembers=mem.teammember.split(",")
			message="The project "+pname+" has been edited by the administrator"
			for member in notifymembers:
				newnote=notificationDetails(admissionnumber=member,notification=message)
				key=newnote.put()
				idnum=key.id()
				newnote.notificationid=str(idnum)
				newnote.put()
		elif is_delete:
			project=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %(projectid))
			for projdetails in project:
				pname=projdetails.projectname
				pteamid=projdetails.teamid
				delfromteam=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %pteamid)
				for team in delfromteam:
					teamprojs=team.projectids.split(",")
					teamuser=team.teammember.split(",")
					for user in teamuser:
						delprojuser=db.GqlQuery("SELECT * FROM userDetails WHERE admissionnumber='%s'" %user)
						for delproj in delprojuser:
							userprojects=delproj.projectids.split(",")
							for projs in userprojects:
								if(projs==projectid):
									userprojects.remove(projectid)
							for prjcts in userprojects:
								userprojs=''
								for prjcts in projs:
									if not userprojs:
										userprojs=prjcts
									else:
										userprojs=userprojs+","+prjcts
							delproj.projectids=userprojs
							delproj.put()
							
					for projid in teamprojs:
						if(projid==projectid):
							teamprojs.remove(projectid)
					teamprojs=''
					for projid in teamprojs:
						if not teamprojs:
							teamprojs=projid
						else:
							teamprojs=teamprojs+","+projid
					team.projectids=teamprojs
					team.put()
				projdetails.delete()
			teammembers=db.GqlQuery("SELECT * FROM teamDetails WHERE teamid='%s'" %(pteamid))
			for member in teammembers:
				notifymembers=member.teammember.split(",")
				message="The project '"+pname+"' has been deleted by the administrator"
				for singlemember in notifymembers:
					newnote=notificationDetails(admissionnumber=singlemember,notification=message)
					key=newnote.put()
					idnum=key.id()
					newnote.notificationid=str(idnum)
					newnote.put()
		elif is_cancel:
			self.redirect("/editprojectmain")
		else:
			raise Exception('no form action given')
		self.redirect("/editprojectmain")

	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		global projectid
		projectid=''
		url = self.request.url
		for i in range(0,len(url),1):
			if(url[i]=='?'):
				i=i+1
				while(url[i]!='='):
					projectid=projectid+url[i]
					i=i+1
				break
		projects=db.GqlQuery("SELECT * FROM projectDetails WHERE projectid='%s'" %projectid)
		path = os.path.join(os.path.dirname(__file__),'editproject.html')#use template
		tmp=[]
		for project in projects:
			categoryselected=[]
			fieldsselected=[]
			languageselected=[]
			categoryunselected=[]
			fieldsunselected=[]
			languageunselected=[]
			catdet=db.GqlQuery("SELECT * FROM projectCategory")
			for catg in catdet:
				if catg.categoryid==project.category:
					categoryselected.append(catg.categoryid)
					categoryselected.append(catg.categorytype)
				else:
					tmp=[]
					tmp.append(catg.categoryid)
					tmp.append(catg.categorytype)
					categoryunselected.append(tmp)
			langdet=db.GqlQuery("SELECT * FROM languages")
			for lang in langdet:
				selflag=0
				for sellang in project.languages:
					if lang.languageid==sellang:
						tmp=[]
						tmp.append(lang.languageid)
						tmp.append(lang.language)
						languageselected.append(tmp)
						selflag=1
						break
				if selflag==0:
					tmp=[]
					tmp.append(lang.languageid)
					tmp.append(lang.language)
					languageunselected.append(tmp)
			fielddet=db.GqlQuery("SELECT * FROM projectFields")
			for fld in fielddet:
				selflag=0
				for indfield in project.fieldnames:
					if fld.fieldid==indfield:
						tmp=[]
						tmp.append(fld.fieldid)
						tmp.append(fld.fieldname)
						fieldsselected.append(tmp)
						selflag=1
						break
				if selflag==0:
					tmp=[]
					tmp.append(fld.fieldid)
					tmp.append(fld.fieldname)
					fieldsunselected.append(tmp)
			self.response.out.write(template.render(path,{"pname":project.projectname,"abstract":project.abstract,"teamid":project.teamid,"categoryunselected":categoryunselected,"categoryselected":categoryselected,"languageunselected":languageunselected,"languageselected":languageselected,"fieldsunselected":fieldsunselected,"fieldsselected":fieldsselected,"reviewdate":project.reviewdate,"maxmembers":project.maxmembers}))#using template


class EditProjectMain(webapp.RequestHandler):
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='admin':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/user")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
		self.verifyLogin()
		confirmed=db.GqlQuery("SELECT * FROM projectDetails")
		path = os.path.join(os.path.dirname(__file__),'editprojectmain.html')#use template
		tmp=[]
		for project in confirmed:
			tmp1=[]
			tmp1.append(project.projectname)
			tmp1.append(project.projectid)
			tmp.append(tmp1)
		self.response.out.write(template.render(path,{"projects":tmp}))#using template

application = webapp.WSGIApplication([('/editproject', EditProject),('/editprojectmain', EditProjectMain)], debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
